#[cfg(windows)]
use rdev::{listen, Event, EventType, Key};
#[cfg(windows)]
use std::sync::{
    atomic::{AtomicBool, Ordering},
    Arc,
};
#[cfg(windows)]
use std::thread;
#[cfg(windows)]
use tauri::AppHandle;
use tauri::Emitter;
use tauri::Manager;

#[tauri::command]
fn greet(name: &str) -> String {
    format!("Hello, {}! You've been greeted from Rust!", name)
}

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    tauri::Builder::default()
        .plugin(tauri_plugin_opener::init())
        .plugin(tauri_plugin_global_shortcut::Builder::new().build())
        .invoke_handler(tauri::generate_handler![greet])
        .setup(|app| {
            let window = app.get_webview_window("main").unwrap();
            #[cfg(windows)]
            window.set_ignore_cursor_events(true)?;
            // window.open_devtools();
            // 全局键盘监听，事件转发到前端
            #[cfg(windows)]
            {
                let running = Arc::new(AtomicBool::new(true));
                let running_clone = running.clone();
                let app_handle: AppHandle = app.handle().clone();
                thread::spawn(move || {
                    let callback = move |event: Event| {
                        if !running_clone.load(Ordering::Relaxed) {
                            panic!("Stop listen thread");
                        }
                        if let EventType::KeyPress(key) = event.event_type {
                            // 将按键名转为字符串
                            let key_str = format!("{:?}", key);
                            let _ = app_handle.emit("global_key", Some(key_str));
                        }
                    };
                    let _ = listen(callback);
                });
                // WebviewWindow 没有 listen，可以用 on_window_event 监听关闭
                let running_close = running.clone();
                window.on_window_event(move |event| {
                    if let tauri::WindowEvent::CloseRequested { .. } = event {
                        running_close.store(false, Ordering::Relaxed);
                    }
                });
            }
            window.set_position(tauri::Position::Logical(tauri::LogicalPosition {
                x: -10.0, // 右移4像素
                y: -10.0,
            }))?;
            Ok(())
        })
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
